import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { SearchBar, ProductCard, BackButton, LoadingSpinner, EmptyState } from '../../components';
import api from '../../../../shared/api';
import './index.css';

const SearchPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);

  // 搜索商品
  const handleSearch = async (searchKeyword: string) => {
    if (!searchKeyword.trim()) return;
    
    setLoading(true);
    setHasSearched(true);
    
    try {
      const result = await api.product.searchProducts(searchKeyword);
      setProducts(result.list || []);
    } catch (error) {
      console.error('搜索失败:', error);
      setProducts([]);
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时如果有关键词就搜索
  useEffect(() => {
    const urlKeyword = searchParams.get('keyword');
    if (urlKeyword) {
      handleSearch(urlKeyword);
    }
  }, [searchParams]);

  const handleProductClick = (productId: string) => {
    navigate(`/mall/product/${productId}`);
  };

  const handleBack = () => {
    navigate(-1);
  };

  return (
    <div className="search-page">
      {/* 头部搜索栏 */}
      <div className="search-page__header">
        <BackButton onClick={handleBack} />
        <div className="search-page__search-bar">
          <SearchBar
            placeholder="请输入商品名称"
            onSearch={handleSearch}
          />
        </div>
      </div>

      {/* 搜索结果 */}
      <div className="search-page__content">
        {loading && (
          <div className="search-page__loading">
            <LoadingSpinner />
          </div>
        )}

        {!loading && hasSearched && products.length === 0 && (
          <EmptyState
            title="没有找到相关商品"
            description="试试其他关键词吧"
            icon="🔍"
          />
        )}

        {!loading && products.length > 0 && (
          <>
            <div className="search-page__result-info">
              找到 {products.length} 个相关商品
            </div>
            <div className="search-page__product-list">
              {products.map((product) => (
                <ProductCard
                  key={product.id}
                  {...product}
                  onProductClick={handleProductClick}
                />
              ))}
            </div>
          </>
        )}

        {!hasSearched && (
          <div className="search-page__placeholder">
            <div className="search-page__placeholder-icon">🔍</div>
            <div className="search-page__placeholder-text">输入关键词搜索商品</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default SearchPage; 